package com.meichis.yndms.ui.activity;

import android.graphics.Color;
import android.os.CountDownTimer;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;

import com.meichis.mcsappframework.gesturelockview.CustomLockView;
import com.meichis.mcsappframework.http.CallManager;
import com.meichis.mcsappframework.utils.ActivityUtils;
import com.meichis.mcsappframework.utils.MessageTools;
import com.meichis.mcsappframework.utils.SharePreferenceUtil;
import com.meichis.mcsappframework.utils.Tools;
import com.meichis.yndms.MCApplication;
import com.meichis.yndms.R;
import com.meichis.yndms.common.APIWEBSERVICE;
import com.meichis.yndms.common.MCode;
import com.meichis.yndms.databinding.ActivityLoginBinding;
import com.meichis.yndms.dialog.AppUpdateDialog;
import com.meichis.yndms.model.UserInfo;
import com.meichis.yndms.repository.manager.BaseManager;
import com.meichis.yndms.repository.manager.TokenManager;
import com.meichis.yndms.ui.common.BaseActivity;
import com.meichis.yndms.vm.AppUpdateVM;
import com.meichis.yndms.vm.LoginVM;

public class LoginActivity extends BaseActivity {

    private ActivityLoginBinding binding;
    private LoginVM vm;
    private AppUpdateVM appUpdateVM;


    @Override
    protected void setDataBindingContentView() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_login);
        vm = new ViewModelProvider(this, new ViewModelProvider.AndroidViewModelFactory(getApplication())).get(LoginVM.class);
        appUpdateVM = new ViewModelProvider(this, new ViewModelProvider.NewInstanceFactory()).get(AppUpdateVM.class);
        binding.setVm(vm);
        binding.setClick(new ClickEvent());
        binding.setLifecycleOwner(this);
        binding.cbShowPsd.setOnCheckedChangeListener((compoundButton, isChecked) -> {
            if (isChecked) {
                binding.etPsd.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
            } else {
                binding.etPsd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
            }
        });
        if ("https://sfa.eyili.com/".equals(APIWEBSERVICE.REMOTE_MCSWSIAPI)) {//如果是测试地址
            binding.tvAddr.setTextColor(Color.RED);
            binding.tvAddr.setTextSize(25);
            binding.tvAddr.setText("当前为测试版");
            binding.llShezhi.setVisibility(View.GONE);
        }
    }

    @Override
    protected void init() {
        ActivityUtils.getInstance().FinishActivityExcept(this.getLocalClassName());
        vm.setUserName(util.getStringValue(SharePreferenceUtil.PREFERENCES_USERNAME));
        if (TextUtils.isEmpty(binding.lvLock.getPassWord())) {
            binding.vfViewFlipper.clearAnimation();
            binding.vfViewFlipper.setDisplayedChild(1);
        } else {
            binding.lvLock.setMode(CustomLockView.LockMode.VERIFY_PASSWORD);
            binding.etPsd.setText(util.getStringValue(SharePreferenceUtil.PREFERENCES_PASSWORD));
        }

        initLock();
        addObserver();
    }

    private void initLock() {
        binding.lvLock.setOnCompleteListener(new CustomLockView.OnCompleteListener() {
            @Override
            public void onComplete(CustomLockView.LockMode mode) {
                vm.setPassWord(util.getStringValue(SharePreferenceUtil.PREFERENCES_PASSWORD));
                vm.Login();
            }

            @Override
            public void onError(String errorTimes) {
                binding.tvHint.setText("绘制错误，请重新绘制");
            }

            @Override
            public void onPasswordIsShort(int passwordMinLength) {

            }

            @Override
            public void onAginInputPassword(CustomLockView.LockMode mode, String password, int[] indexs) {

            }

            @Override
            public void onInputNewPassword() {

            }

            @Override
            public void onEnteredPasswordsDiffer() {

            }

            @Override
            public void onErrorNumberMany() {
                binding.tvHint.setText("错误次数超过限制，请使用账号登录");
                CountDownTimer timer = new CountDownTimer(60000, 1000) {
                    @Override
                    public void onTick(long millisUntilFinished) {
                        binding.tvHint.setText("错误次数超过限制，请" + millisUntilFinished / 1000 + "秒后再试");
                    }

                    @Override
                    public void onFinish() {
                        binding.tvHint.setText("绘制您的解锁图案");
                        binding.lvLock.clearCurrent();
                    }
                };
                timer.start();// 开始计时　
            }
        });
    }

    private void addObserver() {
        vm.getShowDialog().observe(this, (aBoolean) -> showLoading(aBoolean, false));

        vm.getDspToken().observe(this, dspToken -> {
            util.setCacheValue(SharePreferenceUtil.PREFERENCES_AUTHKEY, vm.getDspToken().getValue().getAccess_token(), vm.getDspToken().getValue().getExpires_in() / 60);
            TokenManager.setToken();
            util.setCacheValue(SharePreferenceUtil.PREFERENCES_REFRESHAUTHKEY, vm.getDspToken().getValue().getRefresh_token(), 30 * 60 * 24);
            appUpdateVM.GetLastVersionInfo();
        });

        vm.getUserInfo().observe(this, user -> {
            if (user == null) {
                util.remove(SharePreferenceUtil.PREFERENCES_AUTHKEY);
                MessageTools.ShowmessageDialog(this, "您的账号不能登录液奶老板App！");
                return;
            }

            UserInfo cur = (UserInfo) util.getObjectValue(SharePreferenceUtil.PREFERENCES_USERINFO);
            util.setObjectValue(SharePreferenceUtil.PREFERENCES_USERINFO, user);
            util.setStringValue(SharePreferenceUtil.PREFERENCES_USERNAME, vm.getUserName());
            util.setStringValue(SharePreferenceUtil.PREFERENCES_PASSWORD, vm.getPassWord());
            if (cur != null && !user.getId().equals(cur.getId())) {
                MessageTools.ShowmessageDialog(this, "切换账号将导致原账号的数据丢失，是否确定登录？", () -> vm.ClearData());
                return;
            }
            if (TextUtils.isEmpty((String) util.getCacheValue(SharePreferenceUtil.PREFERENCES_AUTHKEY))) {
                return;
            }
            vm.GetRotateAdvList();
        });


        vm.getRotateAdv().observe(this, rotateAdv -> {
            if (rotateAdv != null && rotateAdv.getItems().size() > 0) {
                util.setObjectValue(SharePreferenceUtil.PREFERENCES_ROTATEADV, rotateAdv);
            } else {
                util.remove(SharePreferenceUtil.PREFERENCES_ROTATEADV);
            }
            openActivityAndClose(MainTabActivity.class);
            close();
        });

        appUpdateVM.getAppVersion().observe(this, appVersion -> {
            if (appVersion != null) {
                /*获取系统版本号*/
                util.setObjectValue(SharePreferenceUtil.PREFERENCES_SERVERVERISON, appVersion);
                if (appVersion.getCurrentVersion() > Tools.getPackageInfo(MCApplication.getContext()).versionCode) {
                    new AppUpdateDialog(this, appVersion, aVoid -> {
                        vm.GetCurrentUser();
                        return null;
                    }).show();
                    return;
                }
            }
            vm.GetCurrentUser();
        });

    }


    public class ClickEvent {

        public void onChangeLogin() {
            binding.vfViewFlipper.setDisplayedChild(1);
        }

        public void onGesture() {
            if (TextUtils.isEmpty(binding.lvLock.getPassWord())) {
                showMsg("手势密码未设置");
                return;
            }
            binding.vfViewFlipper.setDisplayedChild(0);
        }

        public void gotoSetting() {
            openActivity(DebugActivity.class);
        }
    }

}